﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using WebLog;
namespace VotanetWebSite
{
    public partial class Login_Usuario : System.Web.UI.Page
    {
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        private readonly string PATHCAPTCHA = HttpContext.Current.Server.MapPath("~/Images/CaptchaImages/");
        private List<string> imagesCaptchaList = new List<string>();
        private Captcha c = new Captcha();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsCookieEnabled())
            {
                Response.RedirectPermanent("Mensajes_Error/Cookies_Desactivadas.aspx");
            }

            if (!Page.IsPostBack)
            {
                GenerateCaptcha();
            }
        }

        private void GenerateCaptcha()
        {
            c.Generate(140, 40);
            string code = c.GetCode();
            string imageCaptchaPath = c.SaveImage(PATHCAPTCHA, code);
            imagesCaptchaList.Add(PATHCAPTCHA + imageCaptchaPath);
            Session["captchacode"] = code;

            ImageCaptcha.ImageUrl = "~/Images/CaptchaImages/" + imageCaptchaPath;
        }


        protected bool IsCookieEnabled()
        {
            string url = Request.RawUrl;
            if (Request.QueryString["ComprobarCookie"] == null)
            {
                try
                {
                    HttpCookie c = new HttpCookie("CompruebaCookie", "true");
                    Response.Cookies.Add(c);
                    if (url.IndexOf("?") > 0)
                    {
                        url = url + "&ComprobarCookie=true";
                    }
                    else
                    {
                        url = url + "?ComprobarCookie=true";
                    }
                    Response.Redirect(url);
                }
                catch (Exception e)
                {
                    //pico
                    //var p = e;
                }
            }

            if (!Request.Browser.Cookies || Request.Cookies["CompruebaCookie"] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        protected void BotonEnviar_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                Login();
            }
            else
            {
                Response.RedirectPermanent("Mensajes_Error/JavaScript_Desactivado.aspx");
            }
        }

        protected void Login()
        {
            FormsAuthentication.Initialize();
            Users user = new Users();
            user.rut = txtrut.Text;
            user.password = txtContrasena.Text;
            UserLogic userLogic = new UserLogic();

            ///nuevo !!!! CAPTCHA
            ///
            if (userLogic.ValidateCaptcha(txtCaptcha.Text, Session["captchacode"] as string))
            {
                user = userLogic.GetUserLogic(user, KEY);
                if (user != null)
                {
                    string roles = "";
                    foreach (Rol r in user.usersRoles)
                    {
                        roles += r.description + ";";
                    }

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.rut, DateTime.Now, DateTime.Now.AddMinutes(10), false, roles, FormsAuthentication.FormsCookieName);

                    string encryptCookie = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptCookie);
                    Response.Cookies.Add(cookie);

                    if (!roles.ToLower().Contains("administrador"))
                    {
                        Session["usuario"] = user;
                        Response.RedirectPermanent("~/Acceso_Usuario/Administracion_Votante.aspx");
                    }
                    else
                    {
                        Session["administrador"] = user;
                        Response.RedirectPermanent("~/Acceso_Administrador/Administracion_Votacion.aspx");

                    }
                }
                else
                {
                    CleanForm();
                    Messages.Show(Page, Messages.USER_NOT_EXIST);
                }
            }
            else
            {
                Messages.Show(Page, Messages.INVALID_CAPTCHA);

            }

            DeleteCaptcha();
        }

        private void DeleteCaptcha()
        {
            try
            {
                foreach (string str in imagesCaptchaList)
                {
                    File.Delete(str);
                }
            }
            catch (Exception e)
            {
                //pico...
                Logger logger = Logger.GetInstance;
                logger.WriteLog(e);
            }

            imagesCaptchaList.Clear();
        }


        protected void CleanForm()
        {
            txtrut.Text = string.Empty;
            txtContrasena.Text = string.Empty;
            txtCaptcha.Text = string.Empty;
            //txtContrasena2.Text = string.Empty;
        }

        protected void ImageCaptchaReload_Click(object sender, ImageClickEventArgs e)
        {
            txtCaptcha.Text = string.Empty;
            GenerateCaptcha();
        }


    }
}